package com.easycarebn.main.fragment;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Events;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RatingBar;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.easycarebn.main.utils.Utils;
import com.easycarebn.request.controller.ServerController;
import com.easycarebn.request.controller.SuggestNameType;
import com.easycarebn.request.data.Booking;
import com.easycarebn.request.data.DataItemResponse;
import com.easycarebn.request.data.DoctorDetail;
import com.easycarebn.request.data.StatusCode;
import com.easycarebn.request.data.UserProfile;
import com.easycarebn.request.data.UserResponse;
import com.easycarebn.service.request.OnRequest;
import com.squareup.picasso.Picasso;
import com.timbacsi.main.DetailtActivity;
import com.timbacsi.main.EasyCareApplication;
import com.timbacsi.main.GcmRegister;
import com.timbacsi.main.R;

public class FragmentBookStep1 extends Fragment {// FragmentDrDetailt,
													// FragmentResultSearch

	private View mView;
	private static FragmentBookStep1 fragment = null;

	private int mAddressId;
	private int mDocterId;
	private int mServiceType;
	private int mFistVisit = 0;
	private int mInsurance = 0;

	private String mTimebook;
	private String mDatebook;
	private String mDateShowBook;

	private String mAddress;
	private String mToken;

	private TextView tvDrName;
	private TextView tvDrChuyenKhoa;
	private TextView tvDrPosition;
	private TextView tvRoomAddress;
	private TextView ediadiemkham;

	private ImageView imgDrAvatar;
	private RatingBar rb_dr;

	private ImageView mBtnLike;
	private ImageView btnSendEmail;
	private RadioButton rdChuakham;
	private RadioButton rdDakham;

	private RadioButton rdCobh;
	private RadioButton rdKhongcobh;

	private RadioButton rdBookingForme;
	private RadioButton rdBookingForOther;
	private Button btnDatkhamNoLogin;

	private EditText edReason;
	private EditText edPhone;

	private TextView edBrithday;

	private EditText edName;
	private EditText edEmail;
	// private EditText edAddress;

	private LinearLayout lineBookingOther;
	private LinearLayout lineLoginInvi1;
	private LinearLayout lineLoginInvi2;
	private LinearLayout lineinvite0;
	private LinearLayout lineStep2;
	private UserResponse user = null;
	private LinearLayout lineBookingNoLogin;

	private boolean isBookingfor = true;
	private Calendar mCalBirthday;
	private DoctorDetail mDoctorDetail;
	private String device_token = "";
	private String gcm_id = "";

	public static FragmentBookStep1 newInstance(Bundle data) {
		if (fragment == null)
			fragment = new FragmentBookStep1();
		fragment.setArguments(data);
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mDocterId = getArguments().getInt(Utils.KEY_DOCTOR_ID);
		mServiceType = getArguments().getInt(Utils.KEY_SERVICE_TYPE);
		mTimebook = getArguments().getString(Utils.HOUR_BOOK);
		mDatebook = getArguments().getString(Utils.DATE_BOOK);
		mAddress = getArguments().getString(Utils.ADDRESS_NAME);
		mDateShowBook = getArguments().getString(Utils.DATE_SHOW);

		Log.d("mDocterId", mDocterId + " " + mTimebook + " " + mDatebook);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_datkham_step1, null);
		mView.setVisibility(View.INVISIBLE);

		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		gcm_id = GcmRegister.mGcmId;
		Log.d("onActivityCreated", "gcm_id");

		Utils.setOnTouchHideKeyboard(getActivity(), mView);
		isBookingfor = true;
		rdChuakham = (RadioButton) mView.findViewById(R.id.rdChua);
		rdChuakham.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mFistVisit = 0;
			}
		});

		rdDakham = (RadioButton) mView.findViewById(R.id.rdDakham);
		rdDakham.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mFistVisit = 1;
			}
		});

		rdCobh = (RadioButton) mView.findViewById(R.id.rdbhCo);
		rdCobh.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mInsurance = 0;
			}
		});

		rdKhongcobh = (RadioButton) mView.findViewById(R.id.rdBhkhong);
		rdKhongcobh.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mInsurance = 1;
			}
		});

		rdBookingForme = (RadioButton) mView.findViewById(R.id.rdBookingForMe);
		rdBookingForme.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				isBookingfor = true;
				lineBookingOther.setVisibility(View.GONE);
			}
		});

		rdBookingForOther = (RadioButton) mView
				.findViewById(R.id.rdBookingForOther);
		rdBookingForOther.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				isBookingfor = false;
				lineBookingOther.setVisibility(View.VISIBLE);
			}
		});

		edReason = (EditText) mView.findViewById(R.id.reason);

		lineBookingOther = (LinearLayout) mView
				.findViewById(R.id.lineBookingOther);
		lineBookingNoLogin = (LinearLayout) mView
				.findViewById(R.id.lineBookingNoLogin);
		lineinvite0 = (LinearLayout) mView.findViewById(R.id.lineinvite0);
		lineLoginInvi1 = (LinearLayout) mView.findViewById(R.id.lineLoginInvi1);
		lineLoginInvi2 = (LinearLayout) mView.findViewById(R.id.lineLoginInvi2);
		lineStep2 = (LinearLayout) mView.findViewById(R.id.lineStep2);
		edBrithday = (TextView) mView.findViewById(R.id.edBrithday);
		edBrithday.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mCalBirthday == null) {
					mCalBirthday = Calendar.getInstance();
				}
				new DatePickerDialog(getActivity(), new OnDateSetListener() {

					@Override
					public void onDateSet(DatePicker view, int year,
							int monthOfYear, int dayOfMonth) {
						mCalBirthday.set(Calendar.YEAR, year);
						mCalBirthday.set(Calendar.MONTH, monthOfYear);
						mCalBirthday.set(Calendar.DAY_OF_MONTH, dayOfMonth);
						edBrithday.setText(year + "-" + (1 + monthOfYear) + "-"
								+ dayOfMonth);
					}
				}, mCalBirthday.get(Calendar.YEAR), mCalBirthday
						.get(Calendar.MONTH), mCalBirthday
						.get(Calendar.DAY_OF_MONTH)).show();
			}
		});
		tvDrName = (TextView) mView.findViewById(R.id.tv_dr_name);
		ediadiemkham = (TextView) mView.findViewById(R.id.ediadiemkham);

		tvDrChuyenKhoa = (TextView) mView.findViewById(R.id.tv_dr_chuyen_khoa);
		tvRoomAddress = (TextView) mView
				.findViewById(R.id.tv_dr_clininic_address);
		tvDrPosition = (TextView) mView.findViewById(R.id.tv_dr_position);
		imgDrAvatar = (ImageView) mView.findViewById(R.id.img_dr_avatar);
		rb_dr = (RatingBar) mView.findViewById(R.id.rb_dr_rating);

		mBtnLike = (ImageView) mView.findViewById(R.id.btnLike);
		mBtnLike.setVisibility(View.GONE);
		btnSendEmail = (ImageView) mView.findViewById(R.id.btnSendEmail);
		btnSendEmail.setVisibility(View.GONE);

		Button btnDatkham = (Button) mView.findViewById(R.id.btnDatkham);
		btnDatkham.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				actionBooking();
			}
		});
		btnDatkhamNoLogin = (Button) mView.findViewById(R.id.btnDatkhamNoLogin);
		btnDatkhamNoLogin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				actionBooking();
			}
		});

		user = Utils.getUserLogin(getActivity());

		if (user == null) {
			mToken = null;
			edPhone = (EditText) mView.findViewById(R.id.edPhoneNoLogin);
			edName = (EditText) mView.findViewById(R.id.edHotenNoLogin);
			// edAddress = (EditText) mView.findViewById(R.id.edAddressNoLogin);
			edEmail = (EditText) mView.findViewById(R.id.edEmailNoLogin);
			edName.requestFocus();
			lineLoginInvi1.setVisibility(View.GONE);
			lineLoginInvi2.setVisibility(View.GONE);
			lineBookingNoLogin.setVisibility(View.VISIBLE);
			btnDatkhamNoLogin.setVisibility(View.VISIBLE);
		} else {
			mToken = user.getToken();
			edPhone = (EditText) mView.findViewById(R.id.edPhone);
			edName = (EditText) mView.findViewById(R.id.edHoten);

			// edAddress = (EditText) mView.findViewById(R.id.edAdress);
			lineLoginInvi1.setVisibility(View.VISIBLE);
			lineLoginInvi2.setVisibility(View.VISIBLE);
			lineBookingNoLogin.setVisibility(View.GONE);
			btnDatkhamNoLogin.setVisibility(View.GONE);

		}
		edPhone.setText(user.getUser().getPhone());

		getDocterDetailt();
	}

	public void actionBooking() {

		mAddressId = fragment.getArguments().getInt(Utils.KEY_ADDRESS_ID);

		if (mToken != null) {
			String mReason = edReason.getText().toString().trim();
			if (mReason.isEmpty()) {
				Utils.showMessage(
						getActivity(),
						getResources().getString(
								R.string.ly_do_toi_kham_khong_dc_bo_trong));
				edReason.requestFocus();
				return;
			}

			if (isBookingfor) {

				String mPhone = edPhone.getText().toString().trim();
				if (mPhone.isEmpty()) {
					Utils.showMessage(
							getActivity(),
							getResources().getString(
									R.string.so_dien_thoai_ko_dc_bo_trong));
					edPhone.requestFocus();
					return;
				}

				if (mPhone.length() < 10 || mPhone.length() > 11) {
					Utils.showMessage(
							getActivity(),
							getResources().getString(
									R.string.so_dien_thoai_ko_hop_le));
					edPhone.requestFocus();
					return;
				}

				DetailtActivity.loadding.setVisibility(View.VISIBLE);
				Utils.disableEnableControls(false, mView);

				ServerController.getInstance(getActivity())
						.requestBookingForMe(mToken, mDocterId, mAddressId,
								mDatebook, mTimebook, mPhone, mReason,
								mInsurance, mFistVisit, gcm_id, device_token,
								new OnRequest<Booking>() {

									@Override
									public void onSuccess(Booking data) {
										gotoStep2(data);
									}

									@Override
									public void onError(int errorCode,
											String message) {
										DetailtActivity.loadding
												.setVisibility(View.GONE);
										Utils.disableEnableControls(true, mView);

									}
								});
			} else {
				String mName = edName.getText().toString().trim();
				if (mName.isEmpty()) {
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.nhap_ho_ten));
					edName.requestFocus();
					return;
				}

				String mBrithday = edBrithday.getText().toString().trim();
				if (mBrithday.equalsIgnoreCase(getResources().getString(
						R.string.chon_ngay_sinh))) {
					Utils.showMessage(
							getActivity(),
							getResources().getString(
									R.string.vui_long_chon_ngay_sinh));
					return;
				}

				/*
				 * String mAddress = edAddress.getText().toString().trim(); if
				 * (mAddress.isEmpty()) { Utils.showMessage( getActivity(),
				 * getResources().getString( R.string.vui_long_nhap_dia_chi));
				 * edAddress.requestFocus(); return; }
				 */

				String mPhone = edPhone.getText().toString().trim();
				if (mPhone.isEmpty()) {
					Utils.showMessage(
							getActivity(),
							getResources().getString(
									R.string.so_dien_thoai_ko_dc_bo_trong));
					edPhone.requestFocus();
					return;
				}
				if (mPhone.length() < 10 || mPhone.length() > 11) {
					Utils.showMessage(
							getActivity(),
							getResources().getString(
									R.string.so_dien_thoai_ko_hop_le));
					edPhone.requestFocus();
					return;
				}

				DetailtActivity.loadding.setVisibility(View.VISIBLE);
				Utils.disableEnableControls(false, mView);

				ServerController.getInstance(getActivity())
						.requestBookingForOther(mToken, mDocterId, mAddressId,
								mDatebook, mTimebook, mPhone, mReason,
								mInsurance, mFistVisit, mName, mAddress,
								mBrithday, gcm_id, device_token,
								new OnRequest<Booking>() {

									@Override
									public void onSuccess(Booking data) {
										gotoStep2(data);
									}

									@Override
									public void onError(int errorCode,
											String message) {
										DetailtActivity.loadding
												.setVisibility(View.GONE);
										Utils.disableEnableControls(true, mView);
									}
								});

			}

		} else {
			final String mName = edName.getText().toString().trim();
			if (mName.isEmpty()) {
				Utils.showMessage(getActivity(),
						getResources().getString(R.string.nhap_ho_ten));
				edName.requestFocus();
				return;
			}

			String mPhone = edPhone.getText().toString().trim();
			if (mPhone.isEmpty()) {
				Utils.showMessage(getActivity(),
						getResources().getString(R.string.nhap_so_dien_thoai));
				edPhone.requestFocus();
				return;
			}

			final String mEmail = edEmail.getText().toString().trim();
			if (mEmail.isEmpty()) {
				Utils.showMessage(getActivity(),
						getResources().getString(R.string.nhap_email));
				edEmail.requestFocus();
				return;
			}

			if (!mEmail.isEmpty()
					&& !Utils.validate(mEmail, Utils.EMAIL_PATTERN)) {
				Utils.showMessage(getActivity(),
						getResources().getString(R.string.nhap_email_notmarth));
				edEmail.requestFocus();
				return;
			}

			/*
			 * String mAddress = edAddress.getText().toString().trim(); if
			 * (mAddress.isEmpty()) { Utils.showMessage(getActivity(),
			 * getResources() .getString(R.string.vui_long_nhap_dia_chi));
			 * edAddress.requestFocus(); return; }
			 */

			String mReason = edReason.getText().toString().trim();
			if (mReason.isEmpty()) {
				Utils.showMessage(getActivity(),
						getResources().getString(R.string.vui_long_nhap_ly_do));
				edReason.requestFocus();
				return;
			}
			DetailtActivity.loadding.setVisibility(View.VISIBLE);
			Utils.disableEnableControls(false, mView);
			ServerController.getInstance(getActivity()).requestBookingNotLogin(
					mDocterId, mAddressId, mDatebook, mTimebook, mPhone,
					mReason, mInsurance, mName, mAddress, mEmail, 1, gcm_id,
					device_token, new OnRequest<Booking>() {

						@Override
						public void onSuccess(Booking data) {
							if (data.getCode() == StatusCode.OK) {
								user = new UserResponse();
								user.setToken(data.getLoginToken());

								UserProfile userProfile = new UserProfile();
								userProfile.setEmail(mEmail);
								userProfile.setFull_name(mName);

								user.setUser(userProfile);
								EasyCareApplication mEaApplication = (EasyCareApplication) getActivity()
										.getApplicationContext();
								mEaApplication.setLogin(true);

								Utils.updateUserLogin(getActivity(), user);
								gotoStep2(data);
							}

						}

						@Override
						public void onError(int errorCode, String message) {
							DetailtActivity.loadding.setVisibility(View.GONE);
							Utils.disableEnableControls(true, mView);
						}

					});

		}
	}

	public void gotoStep2(DataItemResponse data) {

		DetailtActivity.loadding.setVisibility(View.GONE);
		Utils.disableEnableControls(true, mView);
		if (data == null)
			return;
		if (data.getCode() == StatusCode.OK) {
			lineStep2.setVisibility(View.VISIBLE);
			lineLoginInvi2.setVisibility(View.GONE);
			lineinvite0.setVisibility(View.GONE);
			FragmentBook.callBack.onDisplay(Utils.BOOK_STEP2, "");
			addCalendarEvent();
		}
	}

	public void addCalendarEvent() {
		Calendar c = null;
		try {
			String date[] = mDatebook.split("-");
			String time[] = mTimebook.split(":");

			c = Calendar.getInstance();
			c.set(Integer.parseInt(date[0]), Integer.parseInt(date[1]) - 1,
					Integer.parseInt(date[2]) - 1,
					Integer.parseInt(time[1]) - 1, Integer.parseInt(time[1]), 0);
		} catch (Exception e) {
			// TODO: handle exception
		}

		if (c == null) {
			return;
		}

		if (Build.VERSION.SDK_INT >= 14) {
			Intent intent = new Intent(Intent.ACTION_INSERT)
					.setData(Events.CONTENT_URI)
					.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME,
							c.getTimeInMillis())
					.putExtra(CalendarContract.EXTRA_EVENT_END_TIME,
							c.getTimeInMillis() + 60 * 60 * 1000)
					.putExtra(
							Events.TITLE,
							String.format(
									getResources().getString(
											R.string.dat_kham_bac_si),
									mDoctorDetail.getName()))
					.putExtra(
							Events.DESCRIPTION,
							String.format(
									getResources().getString(
											R.string.dat_kham_bac_si),
									mDoctorDetail.getName()))
					.putExtra(Events.EVENT_LOCATION, mDoctorDetail.getName())
					.putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY);
			startActivity(intent);
		} else {
			Intent intent = new Intent(Intent.ACTION_EDIT);
			intent.setType("vnd.android.cursor.item/event");
			intent.putExtra("beginTime", c.getTimeInMillis());
			intent.putExtra("allDay", true);
			intent.putExtra("rrule", "FREQ=YEARLY");
			intent.putExtra("endTime", c.getTimeInMillis() + 60 * 60 * 1000);
			intent.putExtra("title", String.format(
					getResources().getString(R.string.dat_kham_bac_si),
					mDoctorDetail.getName()));
			startActivity(intent);
		}

	}

	@Override
	public void onPause() {
		super.onPause();
		RequestQueue queue = Volley.newRequestQueue(getActivity());
		queue.cancelAll(new RequestQueue.RequestFilter() {
			@Override
			public boolean apply(Request<?> request) {
				return true;
			}
		});
	}

	public void getDocterDetailt() {
		TextView dateBook = (TextView) mView.findViewById(R.id.your_date_book);
		String date_book = String.format(
				getResources().getString(R.string.lich_kham_cua_ban), Utils
						.setTextcolorHtml(mTimebook + ", " + mDateShowBook,
								"#00a3e0"));
		dateBook.setText(Html.fromHtml(date_book));

		DetailtActivity.loadding.setVisibility(View.VISIBLE);
		ServerController.getInstance(getActivity()).requestGetDoctorDetail(
				mDocterId, mServiceType, mToken, new OnRequest<DoctorDetail>() {

					@Override
					public void onSuccess(DoctorDetail data) {
						if(getActivity()==null)
							return;
						
						mDoctorDetail = data;
						DetailtActivity.loadding.setVisibility(View.GONE);
						mView.setVisibility(View.VISIBLE);

						if (data == null) {
							return;
						}
						/*
						 * String address = ""; if (mServiceType ==
						 * SuggestNameType.DOCTOR.getCode()) { if
						 * (mDoctorDetail.getAddress().isEmpty()) { address =
						 * getResources().getString( R.string.dang_cap_nhat); }
						 * else { address = mDoctorDetail.getAddress(); } } else
						 * { if (mDoctorDetail.getAddress2().isEmpty()) {
						 * address = getResources().getString(
						 * R.string.dang_cap_nhat); } else { address =
						 * mDoctorDetail.getAddress2(); } }
						 */
						if (!mAddress.equals(" ")) {
							ediadiemkham.setText(mAddress);
						} else {
							ediadiemkham.setText(mDoctorDetail.getAddress());
						}

						tvDrName.setText(data.getName());

						Picasso.with(getActivity()).load(data.getAvatar())
								.placeholder(R.drawable.avata)
								.error(R.drawable.avata).into(imgDrAvatar);

						if (data.getPosition() == null
								|| data.getPosition().isEmpty()) {
							tvDrPosition.setVisibility(View.GONE);
						} else {
							tvDrPosition.setText(Html.fromHtml(data
									.getPosition()));
						}

						if (mServiceType == SuggestNameType.DOCTOR.getCode()) {
							if (data.getAddress().isEmpty()) {
								Utils.setTextEmpty(tvRoomAddress, getActivity());
							} else {
								tvRoomAddress.setText(Html.fromHtml(data
										.getAddress()));
							}
						} else {
							// if (data.getAddress2().isEmpty()) {
							// Utils.setTextEmpty(tvRoomAddress, getActivity());
							// } else {
							// tvRoomAddress.setText(Html.fromHtml(data.getAddress2()));
							// }
							Utils.setAddress(tvRoomAddress,
									data.getList_address());
						}

						TextView lblDesc = (TextView) mView
								.findViewById(R.id.lblDesc);
						if (data.getRating() == 0) {
							lblDesc.setVisibility(View.VISIBLE);
							rb_dr.setVisibility(View.GONE);
						} else {
							lblDesc.setVisibility(View.GONE);
							rb_dr.setRating(data.getRating());
						}
						if (data.getSpeciality() != null
								&& !data.getSpeciality().isEmpty()) {
							tvDrChuyenKhoa.setText(String.format(
									getActivity().getResources().getString(
											R.string.chuyen_khoa_bs), data
											.getSpeciality().get(0)));
						} else {
							if (data.getClinictype() != null
									&& data.getClinictype().size() > 0) {
								tvDrChuyenKhoa.setText(data.getClinictype()
										.get(0));
							} else {
								tvDrChuyenKhoa.setVisibility(View.GONE);
							}
						}

					}

					@Override
					public void onError(int errorCode, String message) {
						DetailtActivity.loadding.setVisibility(View.GONE);
					}
				});
	}

}
